$(function () {
  var layer;
  layui.use('layer', function () {
    layer = layui.layer;
  });

  $(".f-rule input[type=checkbox]").ionCheckRadio();
  $(".last input[type=checkbox]").ionCheckRadio();
  $(".fr input[type=checkbox]").ionCheckRadio();

  $(".icr-label").on("change", function () {
    if ($(this).hasClass("checked")) {
      $(this).parent().next().find('input').removeAttr("disabled", "disabled");
    } else {
      $(this).parent().next().find('input').attr("disabled", "disabled");
    }
  })

  jQuery("#verified").slide({
    titCell: ".verified-nav li",
    mainCell: ".verified-bd",
    targetCell: ".verified-form",
    trigger: "click"
  });

  $(".verified-nav ul li").click(function () {
    uploader.destroy();
    initWebUploader();
  })

  $(".cancel").click(function () {
    $(this).parent().siblings('.error').remove();
    $(this).parent().siblings('img').parent('li').removeClass('show');
    $(this).parent().siblings('img').parent('div').removeClass('show');
    $(this).parent().siblings('.plus').find(".webuploader-pick").show();
    $(this).parent().addClass('hide');
    uploader.destroy();
    initWebUploader();
  });

  $(".personform").validate({
    ignore: [],
    rules: {
      authName: {
        required: true
      },
      documetNo: {
        required: true
      },
      documentImgPositive: {
        required: true
      },
      documentImgBack: {
        required: true
      }
    },
    messages: {
      authName: "请输入姓名",
      documetNo: "请输入身份证号码",
      documentImgPositive: "请上传身份证正面图片",
      documentImgBack: "请上传身份证背面图片",
    },
    onsubmit: true,
    errorPlacement: function (error, element) {
      layer.msg($(error).html());
    },
    submitHandler: function (form) {
      var params = $(form).serializeJSON();
      var index = layer.load(1, {shade: [0.1, '#fff']});
      $.ajax({
        url: '/copyright/realNameAuth/person/save',
        type: 'POST',
        data: JSON.stringify(params),
        contentType: 'application/json',
        dataType: 'json',
        success: function (result) {
          if (result.success) {
            location.href = '/copyright/realname/authentication/success';
          } else {
            layer.msg('认证失败，失败原因：' + result.message);
          }
          layer.close(index);
        }
      })
    }
  });

  var validator = $(".enterpriseform").validate({
    rules: {
      authName: {
        required: true
      },
      documetNo: {
        required: true
      },
      legalName: {
        required: true
      },
      legalIdentityCardNo: {
        required: true
      }
    },
    message: {
      legalIdentityCardNo: {
        required: '法人身份证号不能为空'
      }
    },
    onsubmit: true,
  });

  $('#form-company-sub').click(function () {
    var params = $('.enterpriseform').serializeJSON();
    var success = validator.form();

    if (success) {
      var index = layer.load(1, {shade: [0.1, '#fff']});
      $.ajax({
        url: '/copyright/realNameAuth/enterprise/save',
        type: 'POST',
        data: JSON.stringify(params),
        contentType: 'application/json',
        dataType: 'json',
        success: function (result) {
          if (result.success) {
            location.href = '/copyright/realname/authentication/success'
          } else {
            layer.msg('认证失败，失败原因：' + result.message);
          }
          layer.close(index);
        }
      })
    } else {
      if (params.legalIdentityCardNo) {
        layer.msg('请上传营业执照');
      } else {
        layer.msg('请输入法人身份证号码');
      }
    }
    return false;
  });

  var formData = {},
      expire = 0;

  function get_signature() {
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3000) {
      $.ajax({
            url: '/oss/getCertPolicy',
            dataType: 'json',
            async: false,
            success: function (result) {
              if (result.success) {
                formData = $.extend(formData, result.data);
                formData.success_action_status = "200";
                formData.OSSAccessKeyId = result.data.accessid;
                expire = result.expire;
              }
            }
          }
      )
    }

  }

  var uploader = null;

  if (uploader == null) {
    initWebUploader();
  }

  function initWebUploader() {
    uploader = WebUploader.create({

      // swf文件路径
      swf: '/static/front/webuploader/Uploader.swf',

      auto: true,

      thumb: {
        width: 336,
        height: 202,

        // 图片质量，只有type为`image/jpeg`的时候才有效。
        quality: 90,

        // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
        allowMagnify: false,

        // 是否允许裁剪。
        crop: false,
      },

      // 文件接收服务端。
      server: 'http://meisudci.oss-cn-beijing.aliyuncs.com',
      // 内部根据当前运行是创建，可能是input元素，也可能是flash.
      pick: '.wupicker',

      // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
      resize: false,
      accept: {
        title: 'Images',
        extensions: 'gif,jpg,jpeg,bmp,png',
        mimeTypes: 'image/jpg,image/gif,image/jpeg,image/png,image/bmp'
      },
    });

    uploader.on('fileQueued', function (file) {
      var $imgBox = $("#rt_" + file.source.ruid).closest('.plus');
      $imgBox.find(".webuploader-pick").hide();
      var $load = $imgBox.next('.load');
      $load.show();
      var fileName = Util.nuid() + "." + file.ext;
      formData.fileName = fileName;
    })

    uploader.on('uploadBeforeSend', function (obj, data, headers) {
      get_signature();
      formData.key = formData.dir + "/" + formData.fileName;
      $.extend(data, formData);
    });

    uploader.on('uploadSuccess', function (file, response) {
      var $verifiednav = $(".verified-nav"),
          $imgBox = $("#rt_" + file.source.ruid).closest('.plus'),
          $load = $imgBox.next('.load'),
          $cardImg = $imgBox.siblings('.card-img'),
          $li = $cardImg.parent('li'),
          $license_img = $imgBox.siblings('.license-img'),
          $li_license = $license_img.parent();
      var certImgUrl = "http://meisudci.oss-cn-beijing.aliyuncs.com/"
          + formData.key;
      var isBack = $imgBox.parents("li").hasClass("last");
      var idCardSide = "front";
      if (isBack) {
        idCardSide = "back";
      }
      $imgBox.prev('input:hidden').val(certImgUrl);
      var isPerson = $verifiednav.find('ul li:first').hasClass('on');

      //生成缩略图
      uploader.makeThumb(file, function (error, ret) {
        if (error) {
          $cardImg.text('预览错误');
        } else {
          if (isPerson) {
            $cardImg.attr('src', ret);
            $li.addClass('show');
          } else {
            $license_img.attr('src', ret);
            $li_license.addClass('show');
          }

        }
      });

      if (isPerson) {
        $cardImg.next().removeClass('hide');
        $.get("/copyright/realNameAuth/ocrIdCard",
            {idCardSide: idCardSide, imageUrl: certImgUrl},
            function (result) {
              $load.fadeOut();
              var $form = $(".verified-form1"),
                  $name = $form.find('input[name="authName"]'),
                  $documetNo = $form.find('input[name="documetNo"]'),
                  $invalidDate = $form.find('input[name="invalidDate"]');
              if (result.success) {
                $(".verified-form1 .f-item2").removeClass("disable");
                if ('front' == idCardSide) {
                  var data = JSON.parse(result.data),
                      name = data.words_result.姓名.words,
                      idCardNo = data.words_result.公民身份号码.words;

                  $name.val(name);
                  $documetNo.val(idCardNo);
                } else {
                  var data = JSON.parse(result.data),
                      expireDate = data.words_result.失效日期.words;
                  var $longTermEffective = $form.find(
                      'input[name="longTermEffective"]'),
                      $invalidDate = $form.find('input[name="invalidDate"]');
                  if ("长期" == expireDate) {
                    $longTermEffective.click();
                    $longTermEffective.val(1);
                  } else {
                    $longTermEffective.val(0);
                    $longTermEffective.attr('checked', false);
                    expireDate = expireDate.substring(0, 4) + '-'
                        + expireDate.substring(4, 6) + '-'
                        + expireDate.substring(6, 8)
                    $invalidDate.val(expireDate);
                  }
                }

              } else {
                $cardImg.after('<p class="error">识别出错，请手动填写证件信息</p>');
                $name.attr('readonly', false).attr('placeholder', '请输入姓名');
                $documetNo.attr('readonly', false).attr('placeholder',
                    '请输入证件号码');
                $invalidDate.attr('readonly', false).attr('placeholder',
                    '请输入有效期,格式yyyy-MM-dd');
                $('.f-inputs li label').removeClass('readonly');
              }
            }, 'json')
      } else {
        $license_img.next().removeClass('hide');
        $.get('/copyright/realNameAuth/ocrBusinessLicense',
            {imageUrl: certImgUrl}, function (result) {
              $load.fadeOut();
              if (result.success) {
                $(".verified-form2 .f-item2").removeClass("disable");
                var data = JSON.parse(result.data),
                    authName = data.words_result.单位名称.words,
                    legalName = data.words_result.法人.words,
                    expireDate = data.words_result.有效期.words,
                    documentNo = data.words_result.社会信用代码.words;
                var $form = $(".verified-form2"),
                    $authName = $form.find('input[name="authName"]'),
                    $legalName = $form.find('input[name="legalName"]'),
                    $documetNo = $form.find('input[name="documetNo"]'),
                    $longTermEffective = $form.find( 'input[name="longTermEffective"]'),
                    $invalidDate = $form.find('input[name="invalidDate"]');

                if (authName == '无' || legalName == '无' || documentNo == '无') {
                  $license_img.next().removeClass('hide');
                  $license_img.after('<p class="error">识别出错,请手动输入信息</p>');
                  $authName.attr('readonly', false).attr('placeholder','请输入企业名称');
                  $legalName.attr('readonly', false).attr('placeholder','请输入法人名称');
                  $documetNo.attr('readonly', false).attr('placeholder','请输入证件号码');
                  $invalidDate.attr('readonly', false).attr('placeholder','请输入营业执照有效期，格式yyyy-MM-dd');
                  return false;
                }

                $authName.val(authName);
                $legalName.val(legalName);
                $documetNo.val(documentNo.substring(0, 18));

                if (expireDate.indexOf('年') > 0) {
                  expireDate = expireDate.replace('年', '-').replace('月',
                      '-').replace('日', '-');
                  $longTermEffective.val(0);
                  $invalidDate.val(expireDate);
                }else{
                  $longTermEffective.click();
                  $longTermEffective.val(1);

                }

              } else {
                $license_img.after('<p class="error">' + result.message
                    + '</p>');

              }
            }, 'json')

      }

    });

    uploader.on('uploadError', function (file, reason) {
      console.log(reason);
    })
  }

  $.get('/copyright/getIpAddress', function (ip) {
    $.get('/getIpInfo?ip=' + ip, function (result) {
      if (result.code == 0) {
        var province = result.data.region,
            city = result.data.city;
        $('input[name="province"]').val(province);
        $('input[name="city"]').val(city);

      }
    }, 'json')
  })

})